package com.sahyadri.web.util.service.adpater;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sahyadri.web.bean.User;

@Service
public class JpaUserService implements UserService {
	private static final Log log= LogFactory.getLog(JpaUserService.class);
    private EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    @Transactional
    public boolean getUser(String userName, String password){
    	Query query = getEntityManager().createQuery("select count(u.id) from User u where "
                + "u.username =:username and u.password =:password");
    	 query.setParameter("username", userName);
    	 query.setParameter("password", password);
    	 log.debug("User Authentication result " +query.getSingleResult() );
    	 if(String.valueOf(query.getSingleResult()).equals("1")) {
    		 return true;
    	 }
    	 
    	 return false;
    }
    
    @Override
    @Transactional
    public User getUserByUserName(String userName) {
        Query query = getEntityManager().createQuery("from User u where "
                + "u.username =:username");
        query.setParameter("username", userName);
        return  (query.getResultList() != null && query.getResultList().size() > 0)
                ? (User) (query.getResultList().get(0)) : null;
    }

    @Override
    @Transactional
    public User createUser(User user) {
        getEntityManager().persist(user);
        return user;
        
    }

	@Override
	public String[] getUserRoles(String userName) {
		
		return null;
	}
}
